package com.xiaoshuidi.cloud.module.rooms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoshuidi.cloud.framework.common.pojo.CommonResult;
import com.xiaoshuidi.cloud.framework.common.pojo.PageResult;
import com.xiaoshuidi.cloud.module.rooms.controller.admin.reservation.vo.ReserveGetResp;
import com.xiaoshuidi.cloud.module.rooms.controller.admin.roomentrust.vo.AssignPrincipalVO;
import com.xiaoshuidi.cloud.module.rooms.controller.admin.roomentrust.vo.EntrustTrackRecordVO;
import com.xiaoshuidi.cloud.module.rooms.controller.admin.roomentrust.vo.RoomEntrustAddUpdateVO;
import com.xiaoshuidi.cloud.module.rooms.controller.admin.roomentrust.vo.RoomEntrustPageReqVO;
import com.xiaoshuidi.cloud.module.rooms.controller.admin.roomentrust.vo.RoomEntrustRespVO;
import com.xiaoshuidi.cloud.module.rooms.controller.admin.roomentrust.vo.RoomEntrustStatisticsVO;
import com.xiaoshuidi.cloud.module.rooms.controller.admin.roomentrust.vo.RoomEntrustUpdateStatusVO;
import com.xiaoshuidi.cloud.module.rooms.controller.admin.roomentrust.vo.RoomEntrustVO;
import com.xiaoshuidi.cloud.module.rooms.enums.RoomEntrustStatusEnum;
import com.xiaoshuidi.cloud.module.rooms.mapper.RoomEntrustMapper;
import com.xiaoshuidi.cloud.module.rooms.pojo.RoomEntrust;
import com.xiaoshuidi.cloud.module.rooms.pojo.RoomEntrustTrackRecord;
import com.xiaoshuidi.cloud.module.rooms.repository.RoomEntrustRepository;
import com.xiaoshuidi.cloud.module.rooms.repository.RoomEntrustTrackRecordRepository;
import com.xiaoshuidi.cloud.module.rooms.service.RoomEntrustService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class RoomEntrustServiceImpl extends ServiceImpl<RoomEntrustMapper, RoomEntrust> implements RoomEntrustService {

    private final RoomEntrustRepository roomEntrustRepository;

    private final RoomEntrustTrackRecordRepository roomEntrustTrackRecordRepository;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long roomEntrustAdd(RoomEntrustAddUpdateVO roomEntrustAddUpdateVO) {
        //1.新增委派
        RoomEntrust roomEntrust = new RoomEntrust();
        BeanUtils.copyProperties(roomEntrustAddUpdateVO, roomEntrust);
        roomEntrust.setStatus(RoomEntrustStatusEnum.TBA.getCode());
        roomEntrust.setOperatorId(roomEntrust.getOperatorId());
        roomEntrust.setOperatorName(roomEntrustAddUpdateVO.getOperatorName());
        roomEntrust.setDeptId(roomEntrustAddUpdateVO.getDeptId());
        roomEntrustRepository.save(roomEntrust);
        //2.新增一条委派记录
        RoomEntrustTrackRecord record = new RoomEntrustTrackRecord();
        record.setEntrustId(roomEntrust.getId());
        record.setOperatorId(roomEntrust.getOperatorId());
        record.setOperatorName(roomEntrustAddUpdateVO.getOperatorName());
        record.setDeptId(roomEntrustAddUpdateVO.getDeptId());
        record.setRemark(roomEntrustAddUpdateVO.getOperatorName() + "添加了客户 " + roomEntrustAddUpdateVO.getName());
        roomEntrustTrackRecordRepository.save(record);
        return roomEntrust.getId();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean assignPrincipal(AssignPrincipalVO assignPrincipalVO) {
        //1.1 查看主表的deptId以及原来的操作人
        RoomEntrust re= roomEntrustRepository.getById(assignPrincipalVO.getEntrustId());
        //1.修改委派主表的状态以及跟进人
        RoomEntrust roomEntrust = new RoomEntrust();
        roomEntrust.setId(assignPrincipalVO.getEntrustId());
        roomEntrust.setOperatorId(assignPrincipalVO.getOperatorId());
        roomEntrust.setOperatorName(assignPrincipalVO.getOperatorName());
        roomEntrust.setStatus(RoomEntrustStatusEnum.FOLLOWING.getCode());
        roomEntrustRepository.updateById(roomEntrust);
         // 2.增加指派记录
        RoomEntrustTrackRecord record = new RoomEntrustTrackRecord();
        record.setEntrustId(assignPrincipalVO.getEntrustId());
        record.setOperatorId(assignPrincipalVO.getOperatorId());
        record.setOperatorName(assignPrincipalVO.getOperatorName());
        record.setDeptId(re.getDeptId());
        StringBuffer sb= new StringBuffer();
        sb.append(assignPrincipalVO.getOperatorName() + "将客户指派给了" + assignPrincipalVO.getAssignName());
        if (StringUtils.isNotEmpty(assignPrincipalVO.getRemark())){
            sb.append(",备注:"+assignPrincipalVO.getRemark());
        }
        record.setRemark(sb.toString());
        roomEntrustTrackRecordRepository.save(record);
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean roomEntrustUpdate(RoomEntrustAddUpdateVO roomEntrustAddUpdateVO) {
        //1.修改委派主表并不改变状态
        RoomEntrust roomEntrust = new RoomEntrust();
        BeanUtils.copyProperties(roomEntrustAddUpdateVO, roomEntrust);
        roomEntrust.setOperatorId(roomEntrustAddUpdateVO.getOperatorId());
        roomEntrust.setOperatorName(roomEntrustAddUpdateVO.getOperatorName());
        roomEntrustRepository.updateById(roomEntrust);
        //2.增加日志记录
        //2.1 查看主表的deptId
        RoomEntrust re= roomEntrustRepository.getById(roomEntrustAddUpdateVO.getId());
        //2.2
        RoomEntrustTrackRecord record = new RoomEntrustTrackRecord();
        record.setEntrustId(roomEntrustAddUpdateVO.getId());
        record.setOperatorId(roomEntrustAddUpdateVO.getOperatorId());
        record.setOperatorName(roomEntrustAddUpdateVO.getOperatorName());
        record.setDeptId(re.getDeptId());
        record.setRemark(roomEntrustAddUpdateVO.getOperatorName()+"修改了客户信息");
        roomEntrustTrackRecordRepository.save(record);
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean roomEntrustStatusUpdate(RoomEntrustUpdateStatusVO roomEntrustUpdateStatusVO) {

        //修改主表状态
        RoomEntrust roomEntrust = new RoomEntrust();
        roomEntrust.setId(roomEntrustUpdateStatusVO.getEntrustId());
        roomEntrust.setStatus(roomEntrustUpdateStatusVO.getStatus());
        roomEntrust.setOperatorId(roomEntrustUpdateStatusVO.getOperatorId());
        roomEntrust.setOperatorName(roomEntrustUpdateStatusVO.getOperatorName());
        roomEntrustRepository.updateById(roomEntrust);
        //添加记录
        //2.1 查看主表的deptId
        RoomEntrust re= roomEntrustRepository.getById(roomEntrustUpdateStatusVO.getEntrustId());
        RoomEntrustTrackRecord record = new RoomEntrustTrackRecord();
        record.setEntrustId(roomEntrustUpdateStatusVO.getEntrustId());
        record.setDeptId(re.getDeptId());
        record.setOperatorId(roomEntrustUpdateStatusVO.getOperatorId());
        record.setOperatorName(roomEntrustUpdateStatusVO.getOperatorName());
        StringBuffer sb= new StringBuffer();
        sb.append(roomEntrustUpdateStatusVO.getOperatorName() + "标记客户为:" +
                RoomEntrustStatusEnum.getNameByCode(roomEntrustUpdateStatusVO.getStatus()));
        if (StringUtils.isNotEmpty(roomEntrustUpdateStatusVO.getRemark())){
            sb.append(",备注:"+roomEntrustUpdateStatusVO.getRemark());
        }
        record.setRemark(sb.toString());

        roomEntrustTrackRecordRepository.save(record);
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean roomEntrustDelete(Long entrustId) {
        //1.删除主委托
        roomEntrustRepository.removeById(entrustId);
        //2.删除委托记录
        QueryWrapper<RoomEntrustTrackRecord> wrapper = new QueryWrapper<>();
        wrapper.eq("entrust_id", entrustId);
        roomEntrustTrackRecordRepository.remove(wrapper);
        return true;
    }

    @Override
    public RoomEntrustRespVO getRoomEntrustById(Long entrustId) {
        //查询主记录
        RoomEntrust roomEntrust = roomEntrustRepository.getById(entrustId);
        //组装返回对象
        RoomEntrustRespVO detail = new RoomEntrustRespVO();
        if (roomEntrust!=null) {
            //查询记录表
            QueryWrapper<RoomEntrustTrackRecord> wrapper = new QueryWrapper<>();
            wrapper.eq("entrust_id", entrustId).orderByAsc("update_time");
            List<RoomEntrustTrackRecord> list = roomEntrustTrackRecordRepository.list(wrapper);
            List<EntrustTrackRecordVO> records = list.stream().map(r -> {
                EntrustTrackRecordVO vo = new EntrustTrackRecordVO();
                vo.setRemark(r.getRemark());
                vo.setRecordCreateTime(r.getCreateTime());
                return vo;
            }).collect(Collectors.toList());

            BeanUtils.copyProperties(roomEntrust, detail);
            detail.setStatus(RoomEntrustStatusEnum.getNameByCode(roomEntrust.getStatus()));
            if (roomEntrust.getStatus().equals(RoomEntrustStatusEnum.SIGNING.getCode())||roomEntrust.getStatus().equals(RoomEntrustStatusEnum.GIVEUP.getCode())
                    ||roomEntrust.getStatus().equals(RoomEntrustStatusEnum.INVALID.getCode())){
                detail.setFlag(false);
            }else{
                detail.setFlag(true);
            }
            detail.setRecords(records);
            return detail;
        }
        return null;
    }

    @Override
    public List<RoomEntrustStatisticsVO> getRoomEntrustStatistics() {
        //查询所有的委托主记录
        List<RoomEntrust> list = roomEntrustRepository.list();
        //统计出各个状态下的数量
        List<RoomEntrustStatisticsVO> result = new ArrayList<>();
        for (RoomEntrustStatusEnum v : RoomEntrustStatusEnum.values()) {
            RoomEntrustStatisticsVO vo = new RoomEntrustStatisticsVO();
            vo.setCode(v.getCode());
            vo.setName(v.getName());
            long count = list.stream().filter(r -> r.getStatus().equals(v.getCode())).count();
            vo.setNum(count);
            result.add(vo);
        }
        return result;
    }

    @Override
    public PageResult<RoomEntrustVO> roomEntrustPage(RoomEntrustPageReqVO roomEntrustPageReqVO) {

        Page<RoomEntrust> page = roomEntrustRepository.roomEntrustPage(roomEntrustPageReqVO);
        List<RoomEntrust> records = page.getRecords();
        List<RoomEntrustVO> vos = records.stream().map(r -> {
            RoomEntrustVO vo = new RoomEntrustVO();
            BeanUtils.copyProperties(r,vo);
            if (r.getStatus().equals(RoomEntrustStatusEnum.SIGNING.getCode())|| r.getStatus().equals(RoomEntrustStatusEnum.GIVEUP.getCode())
            ||r.getStatus().equals(RoomEntrustStatusEnum.INVALID.getCode())){
                vo.setFlag(false);
            }else{
                vo.setFlag(true);
            }
            return vo;
        }).collect(Collectors.toList());
        PageResult<RoomEntrustVO> result = new PageResult<>(vos, page.getTotal());
        return result;
    }

    /**
     * 未完成的委托数量
     * @return
     */
    @Override
    public CommonResult<Long> toBeContinuedEntrustNum() {
        LambdaQueryWrapper<RoomEntrust> wrapper = Wrappers.lambdaQuery();
        wrapper.in(RoomEntrust::getStatus, Arrays.asList(
                RoomEntrustStatusEnum.TBA.getCode(),
                RoomEntrustStatusEnum.FOLLOWING.getCode(),
                RoomEntrustStatusEnum.PHONED.getCode(),
                RoomEntrustStatusEnum.REVIEWED.getCode(),
                RoomEntrustStatusEnum.POSTPONED.getCode()
                ));
        long count = roomEntrustRepository.count(wrapper);
        return CommonResult.success(count);
    }
}
